﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Models;
using System.Reflection;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// 2015/08/07
/// liang
/// </summary>
/// 
public partial class _EasyForm : System.Web.UI.Page// AdminBase
{
    Entities db = new Entities();
    private FieldLine line;
    public static object EntitiesObj = new Entities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTables(null);
        }
    }

    private void BindTables(string def)
    {
        tables.Items.Clear();
        List<string> tableNames = getTables();
        tables.DataSource = tableNames;
        tables.DataBind();
        if (tables.Items.Count > 0)
        {
            if (def != null)
            {
                tables.SelectedValue = def;
            }
            else
            {
                tables.Items[0].Selected = true;
            }
            BindTableFields(tableNames);
        }
    }

    private List<string> getTables()
    {
        PropertyInfo[] ps = db.GetType().GetProperties().OrderBy(x => x.Name).ToArray();
        List<string> tablenames = new List<string>();
        string type;
        foreach (var p in ps)
        {
            if (p.PropertyType.IsGenericType)
            {
                type = p.PropertyType.GetGenericTypeDefinition().Name;
                if (type.Contains("ObjectSet") || type.Contains("DbSet"))
                {
                    tablenames.Add(p.Name);
                }
            }
        }

        return tablenames;
    }
    private void BindTableFields(List<string> tablenames)
    {
        head1.Visible = false;
        if (tables.SelectedValue == "")
        {
            return;
        }
        object model = getModObj(tables.SelectedValue);

        if (model != null)
        {
            PropertyInfo[] ps = model.GetType().GetProperties();
            string type = "";
            string name = "";
            bool nullable = false;
            List<TableField> fields = new List<TableField>();
            List<ListItem[]> ctrls = new List<ListItem[]>();
            bool[] NotEmptyArr = new bool[ps.Length];
            string[] types = new string[ps.Length];
            for (int i = 0; i < ps.Length; i += 1)
            {
                name = ps[i].Name;
                type = getTypeName(model, name, out nullable);
                types[i] = type;
                NotEmptyArr[i] = type != "String" && !nullable;

                if (type == "EntityState" || type == "EntityKey")
                {
                    continue;
                }
                fields.Add(new TableField { Name = name, Type = type, NullAble = nullable ? "?" : "" });
                ctrls.Add(getAlowCtrls(type));
            }
            taableFields.DataSource = fields;
            taableFields.DataBind();
            /*主键字段项*/
            prkey.DataSource = fields.Where(x => (x.Type == "Int32" || x.Type == "Int64") && x.NullAble == "");
            prkey.DataTextField = "Name";
            prkey.DataBind();
            /*添加、修改时间字段项*/
            addtime.DataSource = updatatime.DataSource = fields.Where(x => x.Type == "DateTime");
            addtime.DataTextField = updatatime.DataTextField = "Name";
            addtime.DataBind();
            updatatime.DataBind();
            updatatime.Items.Insert(0, new ListItem("-无-", ""));
            addtime.Items.Insert(0, new ListItem("-无-", ""));
            /***********/
            TableField ID = fields.FirstOrDefault(x => (x.Type == "Int32" || x.Type == "Int64") && x.NullAble == "" && x.Name.ToLower().Contains("id"));
            if (ID != null)
            {
                prkey.SelectedValue = ID.Name;
            }
            bool findId = false;
            RepeaterItemCollection items = taableFields.Items;
            for (int i = 0; i < items.Count; i += 1)
            {
                line = new FieldLine(items[i]);
                if (prkey.SelectedValue != "" && !findId && line.fieldname.Text == prkey.SelectedValue)
                {
                    line.cid.Checked = false;
                    line.cid.Enabled = false;
                    line.cid.ToolTip = "主键，不可选";
                    IDFieldType.Text = line.fieldtype.Text;
                }
                line.ctrtype.Items.AddRange(ctrls[i]);
                if (NotEmptyArr[i])
                {
                    line.noempty.Enabled = false;
                }
                if (tablenames != null)// !IsPostBack
                {
                    line.sourcetable.DataSource = tablenames;
                    line.sourcetable.DataBind();
                }
                if (types[i] == "String")
                {
                    head1.Visible = items[i].FindControl("textLenth").Visible = true;
                }
                else if (types[i] == "Boolean")
                {
                    line.textvalues.CssClass = "show focus";
                    if (line.ctrtype.SelectedValue == ControlTypes.CheckBox)
                    {
                        line.textvalues.Text = "是";
                        line.textvalues.CssClass = "text1";
                    }
                    else
                    {
                        line.textvalues.Text = "是|否";
                        line.textvalues.CssClass = "text2";
                    }
                    line.textvalues.Focus();
                    head3.Visible = true;
                }
            }
        }
    }

    protected void OnPryKeyChange(object sender, EventArgs e)
    {
        RepeaterItemCollection items = taableFields.Items;
        CheckBox cid = null;
        foreach (RepeaterItem it in items)
        {
            cid = it.FindControl("cid") as CheckBox;
            if ((it.FindControl("fieldname") as TextBox).Text == prkey.SelectedValue)
            {
                cid.Checked = false;
                cid.Enabled = false;
                cid.ToolTip = "主键，不可选";
                IDFieldType.Text = (it.FindControl("fieldtype") as TextBox).Text;
            }
            else
            {
                cid.Enabled = true;
                cid.ToolTip = "";
            }
        }
    }

    protected void OnAddTiemChange(object sender, EventArgs e)
    {
        RepeaterItemCollection items = taableFields.Items;
        CheckBox cid = null;
        foreach (RepeaterItem it in items)
        {
            cid = it.FindControl("cid") as CheckBox;
            if ((it.FindControl("fieldname") as TextBox).Text == addtime.SelectedValue)
            {
                cid.Checked = false;
                cid.Enabled = false;
                cid.ToolTip = "添加时间，不可选";

            }
            else if ((it.FindControl("fieldtype") as TextBox).Text == "DateTime")
            {
                cid.Enabled = true;
                cid.ToolTip = "";
            }
        }
    }

    private ListItem[] getAlowCtrls(string dataType)
    {
        switch (dataType)
        {
            case "String":
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine), new ListItem(ControlTypes.TextBox_MultiLine), new ListItem(ControlTypes.TextBox_Password)
                    , new ListItem(ControlTypes.DropDownList), new ListItem(ControlTypes.ListBox), new ListItem(ControlTypes.RadioButtonList),new ListItem(ControlTypes.CheckBoxList) };
            case "Int32":
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine), new ListItem(ControlTypes.DropDownList), new ListItem(ControlTypes.ListBox), new ListItem(ControlTypes.RadioButtonList) };
            case "Int64":
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine), new ListItem(ControlTypes.DropDownList), new ListItem(ControlTypes.ListBox), new ListItem(ControlTypes.RadioButtonList) };
            case "Double":
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine), new ListItem(ControlTypes.DropDownList), new ListItem(ControlTypes.ListBox), new ListItem(ControlTypes.RadioButtonList) };
            case "Decimal":
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine), new ListItem(ControlTypes.DropDownList), new ListItem(ControlTypes.ListBox), new ListItem(ControlTypes.RadioButtonList) };
            case "DateTime":
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine) };
            case "Boolean":
                return new ListItem[] { new ListItem(ControlTypes.CheckBox), new ListItem(ControlTypes.RadioButtonList) };
            default:
                return new ListItem[] { new ListItem(ControlTypes.TextBox_SingleLine), new ListItem(ControlTypes.TextBox_MultiLine), new ListItem(ControlTypes.TextBox_Password) };
        }
    }

    protected void onCtrlTypeChange(object sender, EventArgs e)
    {
        tips.Text = "";
        line = new FieldLine((sender as Control).Parent);
        string ctrtype = line.ctrtype.SelectedValue;
        string fieldtype = line.fieldtype.Text;
        if (ctrtype == ControlTypes.DropDownList || ctrtype == ControlTypes.ListBox || ctrtype == ControlTypes.RadioButtonList || ctrtype == ControlTypes.CheckBoxList || ctrtype == ControlTypes.CheckBox)
        {
            head2.Visible = head3.Visible = true;
            line.dataSourcesType.Visible = true;
            line.settextarea.Visible = false;
            line.setboxlist.Visible = ctrtype == ControlTypes.RadioButtonList || ctrtype == ControlTypes.CheckBoxList;
            if (line.dataSourcesType.SelectedValue == "0")
            {
                line.textvalues.Focus();
                line.sourcetable.CssClass = "hidden";
                if (fieldtype == "Boolean")
                {
                    line.dataSourcesType.Visible = false;
                    if (ctrtype == ControlTypes.CheckBox)
                    {
                        line.textvalues.Text = "是";
                        line.textvalues.CssClass = "show focus text1";
                    }
                    else
                    {
                        line.textvalues.Text = "是|否";
                        line.textvalues.ToolTip = "请输入一对文代表真假，本用'|'分割，前一条代表真值,如  是|否   男|女 yes|no";
                        line.textvalues.CssClass = "show focus text2";
                    }
                }
                else
                {
                    line.textvalues.CssClass = "show focus text";
                    head3.Text = "DataSource文本";
                    if (line.textvalues.Text == "")
                    {
                        if (fieldtype == "String")
                        {
                            line.textvalues.Text = "text1|text2|text3";
                            line.textvalues.ToolTip = "请输入多条文本(text)，用'|'分割,程序将生成对应个数的ListItem。DateTextField和DataValueField相同";
                        }

                        else if (fieldtype == "Int32" || fieldtype == "Int64" || fieldtype == "Int16" || fieldtype == "Double" || fieldtype == "Decimal")
                        {
                            line.textvalues.Text = "text1,1|text2,2|text3,3";
                            line.textvalues.ToolTip = "请输入多组文本(text,nuber)，用'|'分割，再用','分割DateTextField和DataValueField,程序将生成对应个数的ListItem。DateTextField为文本，DataValue为数值";
                        }
                        else
                        {
                            line.textvalues.Text = "text1|text2|text3...";
                        }
                    }
                }
            }
            else
            {
                head3.Text = "DataSource-table-TextField-ValueField";
                line.textFiled.CssClass = line.valueFiled.CssClass = line.sourcetable.CssClass = "show";
                line.textvalues.CssClass = "hidden";
            }
        }
        else
        {
            line.settextarea.Visible = line.setboxlist.Visible = line.dataSourcesType.Visible = false;
            if (ctrtype == ControlTypes.TextBox_MultiLine)
            {
                line.settextarea.Visible = true;
            }

            line.textFiled.CssClass = line.valueFiled.CssClass = line.textvalues.CssClass = line.sourcetable.CssClass = "hidden";
        }
    }

    protected void SourceTypeChange(object sender, EventArgs e)
    {
        line = new FieldLine((sender as Control).Parent);
        if (line.dataSourcesType.SelectedValue == "0")
        {
            head3.Text = "DataSource文本";
            line.textFiled.CssClass = line.valueFiled.CssClass = line.sourcetable.CssClass = "hidden";
            line.textvalues.CssClass = "show focus text";
        }
        else
        {
            head3.Text = "DataSource-table-TextField-ValueField";
            line.sourcetable.CssClass = "show";
            line.textvalues.CssClass = "hidden";
            bind_TextField_ValueField(line);
        }
    }

    protected void dataSourrceChange(object sender, EventArgs e)
    {
        tips.Text = "";
        line = new FieldLine((sender as Control).Parent);
        bind_TextField_ValueField(line);
    }

    private void bind_TextField_ValueField(FieldLine line)
    {
        string fieldtype = line.fieldtype.Text;

        object model = getModObj(line.sourcetable.SelectedValue);
        if (model != null)
        {
            PropertyInfo[] ps = model.GetType().GetProperties();
            List<TableField> fields = new List<TableField>();
            string name = "";
            string type = "";
            bool nullable = false;
            foreach (PropertyInfo c in ps)
            {
                name = c.Name;
                type = getTypeName(model, name, out nullable);
                if (type == "EntityState" || type == "EntityKey")
                {
                    continue;
                }
                fields.Add(new TableField { Name = string.Format("{0}/{1}{2}", name, type, nullable ? "?" : ""), Type = type, NullAble = nullable ? "?" : "" });
            }
            line.textFiled.DataSource = fields;
            line.textFiled.DataTextField = line.textFiled.DataValueField =
                line.valueFiled.DataTextField = line.valueFiled.DataValueField = "Name";
            if (fieldtype == "String")
            {
                line.valueFiled.DataSource = fields;
                line.textFiled.DataBind();
                line.textFiled.CssClass = "show";
                line.valueFiled.CssClass = "show";
                line.valueFiled.Items.Clear();
                line.valueFiled.Items.Add("同TextField");
            }
            else
            {
                if (fieldtype == "Double" || fieldtype == "Decimal")
                {
                    line.valueFiled.DataSource = fields.Where(a => a.Type == "Double" || a.Type == "Decimal" || a.Type == "Int32" || a.Type == "Int64");
                }
                else if (fieldtype == "Int64")
                {
                    line.valueFiled.DataSource = fields.Where(a => a.Type == "Int32" || a.Type == "Int64");
                }
                else if (fieldtype == "Int32")
                {
                    line.valueFiled.DataSource = fields.Where(a => a.Type == "Int32" || a.Type == "Int64"); //"Int64" 可能有问题
                }

                line.textFiled.DataBind();
                line.valueFiled.DataBind();
                line.textFiled.CssClass = line.valueFiled.CssClass = "show";
                if (line.valueFiled.Items.Count == 0)
                {
                    line.valueFiled.BorderColor = Color.Red;
                    line.valueFiled.ToolTip = "未找到合适的字段";
                }
            }
            var f = fields.FirstOrDefault(x => x.Type == "String");
            if (f != null)
            {
                line.textFiled.SelectedValue = f.Name;
            }
        }

    }

    protected void creatForm(object sender, EventArgs e)
    {
        tips.Text = "";
        if (tables.SelectedValue == "")
        {
            return;
        }
        if (prkey.SelectedValue == "")
        {
            tips.Text = "未生成，无主键";
            return;
        }
        RepeaterItemCollection items = taableFields.Items;
        StringBuilder sb = new StringBuilder();
        TheFrom form = new TheFrom(tables.SelectedValue,
             Server.MapPath("~/EasyFormPages/"), int.Parse(cols.SelectedValue),
          new string[] { prkey.SelectedValue, addtime.SelectedValue, updatatime.SelectedValue, this.IDFieldType.Text == "Int64" ? "long" : "int" },
          tips, needJsp.Checked, validator.Checked);
        foreach (RepeaterItem item in items)
        {
            if ((item.FindControl("cid") as CheckBox).Checked)
            {
                form.AddLine(new FieldLine(item));
            }
        }
        if (form.LinrSize() == 0)
        {
            tips.Text = "未生成，选择的字段数为0";
            return;
        }
        string msg = "";
        form.CreatCode(ref msg);
    }

    protected void refreshTables(object sender, EventArgs e)
    {
        tips.Text = "";
        BindTables(tables.SelectedValue);
        checkall.Checked = false;
    }

    protected void ReBindTableFields(object sender, EventArgs e)
    {
        tips.Text = "";
        BindTableFields(getTables());
    }

    #region tools
    public string getTypeName(object obj, string name, out bool nullable)
    {
        nullable = false;
        PropertyInfo pi = obj.GetType().GetProperties().FirstOrDefault(a => a.Name.ToLower() == name.ToLower());
        Type columnType = pi.PropertyType;
        if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            columnType = columnType.GetGenericArguments()[0];
            nullable = true;
        }
        return columnType.Name;
    }

    public object getModObj(string tableName)
    {
        Type ts = db.GetType();
        PropertyInfo ps = ts.GetProperties().FirstOrDefault(a => a.Name.ToLower() == tableName.ToLower());
        if (ps == null)
        {
            return null; ;
        }
        var v = ps.GetValue(db, null);
        object model = v.GetType().GetMethods().FirstOrDefault(a => a.Name == "CreateObject" || a.Name == "Create").Invoke(v, null);
        return model;
    }
    #endregion



}

#region toolclass
class FieldLine
{
    private string msg;
    private bool success = true;
    private Control repeater;
    public FieldLine(Control mRepeater)
    {
        this.repeater = mRepeater;
    }

    public Control findContrlById(string id)
    {
        return repeater.FindControl(id);
    }
    public bool IsSuccess()
    {
        return success;
    }

    public string getMsg()
    {
        string s = msg;
        msg = "";
        return s;
    }

    public string ToFormLine(int index, int cols)
    {
        if (cols == 1)
        {
            return string.Format("             <tr>\r\n                  <td class='name_td'>{0}：</td>\r\n                  <td class='value_td'>{1}</td>\r\n             </tr>\r\n", this.labeltext.Text, CreatContrl());
        }
        else
        {
            if (index % cols == 1)
            {
                return string.Format("             <tr>\r\n                  <td class='name_td'>{0}：</td>\r\n                  <td class='value_td'>{1}</td>\r\n", this.labeltext.Text, CreatContrl());
            }
            else if (index % cols == 0)
            {
                return string.Format("                  <td class='name_td'>{0}：</td>\r\n                  <td class='value_td'>{1}</td>\r\n             </tr>\r\n", this.labeltext.Text, CreatContrl());
            }
            else
            {
                return string.Format("                  <td class='name_td'>{0}：</td>\r\n                  <td class='value_td'>{1}</td>\r\n", this.labeltext.Text, CreatContrl());
            }
        }
    }

    public string OnShow()
    {
        string ContrlType = this.ctrtype.SelectedValue;
        string fieldname = this.fieldname.Text;
        string fieldtype = this.fieldtype.Text;
        string contrlName = fieldname;
        bool nullable = this.fieldnull.Text == "?";
        string ToString = fieldtype == "String" ? " " : " \"\" + ";
        if (ContrlType == ControlTypes.TextBox_SingleLine || ContrlType == ControlTypes.TextBox_MultiLine || ContrlType == ControlTypes.TextBox_Password)
        {
            return string.Format("{0}.Text ={1}Data.{2};", contrlName, ToString, fieldname);
        }
        else if (ContrlType == ControlTypes.DropDownList || ContrlType == ControlTypes.ListBox)
        {
            return string.Format("{0}.SelectedValue ={1}Data.{2};", contrlName, ToString, fieldname);
        }
        else if (ContrlType == ControlTypes.RadioButtonList)
        {
            if (fieldtype == "Boolean")
            {
                if (!nullable)
                {
                    return string.Format("{0}.Items[Data.{2} ? 0 : 1].Selected = true;", contrlName, fieldname);
                }
                return string.Format("{0}.Items[Data.{1}.GetValueOrDefault(false) ? 0 : 1].Selected = true;", contrlName, fieldname);
            }
            else
            {
                return string.Format("{0}.SelectedValue ={1}Data.{2};", contrlName, ToString, fieldname);
            }
        }
        else if (ContrlType == ControlTypes.CheckBoxList)
        {
            if (fieldtype == "String")
            {
                return string.Format("BindCheckBoxList({0},Data.{1});", contrlName, fieldname);
            }
        }
        else if (ContrlType == ControlTypes.CheckBox)
        {
            if (!nullable)
            {
                return string.Format("{0}.Checked = Data.{1};", contrlName, fieldname);
            }
            return string.Format("{0}.Checked = Data.{1}.GetValueOrDefault(false);", contrlName, fieldname);
        }

        return "//not-implement";
    }

    public StringBuilder OnBindDataSource()
    {
        string ContrlType = this.ctrtype.SelectedValue;
        string fieldtype = this.fieldtype.Text;
        string fieldname = this.fieldname.Text;
        string contrlName = fieldname;

        if (this.dataSourcesType.SelectedValue != "1")
        {
            return null;
        }
        if (ContrlType == ControlTypes.DropDownList || ContrlType == ControlTypes.ListBox || ContrlType == ControlTypes.CheckBoxList || (ContrlType == ControlTypes.RadioButtonList && fieldtype != "Boolean"))
        {
            if (this.textFiled.Items.Count == 0 || this.valueFiled.Items.Count == 0)
            {
                msg = "错误！缺少textFiled或valueFiled-" + fieldname;
            }
            else if (this.sourcetable.Items.Count == 0)
            {
                msg = "错误！缺少DataSource-" + fieldname;
                success = false;
                return null;
            }
            string text = this.textFiled.SelectedValue.Split('/')[0];
            string value = this.valueFiled.SelectedValue.Split('/')[0];

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("        {0}.DataSource = db.{1}.ToList();\r\n", contrlName, this.sourcetable.SelectedValue);
            sb.AppendFormat("        {0}.DataTextField = \"{1}\";\r\n", contrlName, text);
            sb.AppendFormat("        {0}.DataValueField = \"{1}\";\r\n", contrlName, fieldtype == "String" ? text : value);
            sb.AppendFormat("        {0}.DataBind();\r\n", contrlName);
            sb.AppendFormat("        {0}.Items.Insert(0, new ListItem(\"--请选择--\", \"\"));\r\n", contrlName);
            return sb;
        }

        return null;
    }
    public StringBuilder OnSave()
    {
        string ContrlType = this.ctrtype.SelectedValue;
        string fieldname = this.fieldname.Text;
        string fieldtype = this.fieldtype.Text;
        string contrlName = fieldname;
        bool nullable = this.fieldnull.Text == "?";
        bool noempty = this.noempty.Checked;

        StringBuilder sb = new StringBuilder();
        if (fieldtype == "String")
        {
            bool istext = ContrlType == ControlTypes.TextBox_SingleLine || ContrlType == ControlTypes.TextBox_MultiLine || ContrlType == ControlTypes.TextBox_Password;
            if (istext)
            {
                sb.AppendFormat("        Data.{0} = {1}.Text.Trim();\r\n", fieldname, contrlName);
                int l = 0;
                if (int.TryParse(this.textLenth.Text.Trim(), out l) && l > 0)
                {
                    sb.AppendFormat("        if (Data.{0}.Length > {1})\r\n", fieldname, l);
                    sb.Append("        {\r\n");
                    sb.AppendFormat("            {0}.Focus();\r\n", contrlName);
                    sb.AppendFormat("            {0}", OnError(string.Format("字数应在{0}字以内！", l)));
                    sb.Append("            return;\r\n");
                    sb.Append("        }\r\n");
                }
            }
            else if (ContrlType == ControlTypes.CheckBoxList)
            {
                sb.AppendFormat("        Data.{0} = GetCheckBoxListValues({1});\r\n", fieldname, contrlName);
            }
            else
            {
                sb.AppendFormat("        Data.{0} = {1}.SelectedValue;\r\n", fieldname, contrlName);
            }
            if (noempty)
            {
                sb.AppendFormat("        if (Data.{0} == \"\")\r\n", fieldname, contrlName);
                sb.Append("        {\r\n");
                if (istext)
                {
                    sb.AppendFormat("            {0}.Focus();\r\n", contrlName);
                }
                sb.AppendFormat("            {0}", OnError("不允许为空！"));
                sb.Append("            return;\r\n");
                sb.Append("        }\r\n");
            }
            return sb;
        }
        else if ("Decimal|Int32|Int64|Double|DateTime".Contains(fieldtype))
        {
            string varb = "_" + fieldtype.ToLower();
            string text = ContrlType == ControlTypes.TextBox_SingleLine ? "Text.Trim()" : "SelectedValue"; ;
            sb.AppendFormat("        if ({0}.TryParse({1}.{2}, out {3}))\r\n", fieldtype, contrlName, text, varb);
            sb.Append("        {\r\n");
            sb.AppendFormat("            Data.{0} = {1};\r\n", fieldname, varb);
            sb.Append("        }\r\n");

            if (noempty)
            {
                sb.Append("        else\r\n        {\r\n");
                if (ContrlType == ControlTypes.TextBox_SingleLine)
                {
                    sb.AppendFormat("            {0}.Focus();\r\n", contrlName);
                }
                sb.AppendFormat("            {0}", OnError(string.Format("输入错误，请输入有效的{0}！", fieldtype == "Int32"
                        || fieldtype == "Int64" ? "整数" : fieldtype == "Double" || fieldtype == "Decimal" ? "小数" : "时间")));
                sb.Append("            return;\r\n");
                sb.Append("        }\r\n");
            }
        }
        else if (fieldtype == "Boolean")
        {
            if (ContrlType == ControlTypes.CheckBox)
            {
                return sb.AppendFormat("        Data.{0} = {1}.Checked;\r\n", fieldname, contrlName);
            }
            else
            {
                return sb.AppendFormat("        Data.{0} = {1}.SelectedIndex == 0;\r\n", fieldname, contrlName);
            }
        }
        return sb;
    }

    private string OnError(string msg)
    {
        return string.Format("JscriptPrint(\"{0}\",\"\",\"Error\");\r\n", msg);
    }
    private string CreatContrl()
    {
        string ContrlType = this.ctrtype.SelectedValue;

        string contrlNaeme = this.fieldname.Text;

        if (ContrlType == ControlTypes.CheckBox)
        {
            return string.Format("<asp:CheckBox ID=\"{0}\" runat=\"server\" Text=\"{1}\" {2} />", contrlNaeme, this.textvalues.Text, CssClass(ContrlType));
        }
        else if (ContrlType == ControlTypes.TextBox_SingleLine)
        {
            return string.Format("<asp:TextBox ID=\"{0}\" runat=\"server\" {1} {2} {3} {4}></asp:TextBox>{5}", contrlNaeme, CssClass(ContrlType), SetLength(), IsNumber(), isDateTime(), getValidators());
        }
        else if (ContrlType == ControlTypes.TextBox_MultiLine)
        {
            return string.Format("<asp:TextBox ID=\"{0}\" runat=\"server\" TextMode=\"MultiLine\" {1} {2}></asp:TextBox>{3}", contrlNaeme, CssClass(ContrlType), textCols_Rows()/*, SetLength() */, getValidators());
        }
        else if (ContrlType == ControlTypes.TextBox_Password)
        {
            return string.Format("<asp:TextBox ID=\"{0}\" runat=\"server\" TextMode=\"Password\" {1} {2}></asp:TextBox>{3}", contrlNaeme, CssClass(ContrlType), SetLength(), getValidators());
        }
        else if (new string[] { ControlTypes.DropDownList, ControlTypes.ListBox, ControlTypes.CheckBoxList, ControlTypes.RadioButtonList }.Contains(ContrlType))
        {
            return string.Format("<asp:{1} ID=\"{0}\" runat=\"server\" {2} {3}>{4}</asp:{1}>{5}", contrlNaeme, ContrlType, CssClass(ContrlType), IsLayoutAble(ContrlType), CreatItems(ContrlType), ContrlType != ControlTypes.CheckBoxList ? getValidators() : null);
        }
        msg = string.Format("not-implement - {0}&nbsp;&nbsp;", ContrlType);
        return "not-implement";
    }
    private StringBuilder getValidators()
    {
        StringBuilder sb = new StringBuilder();
        if (!UseValidator || !this.noempty.Checked)
        {
            return sb;
        }
        string _fieldtype = this.fieldtype.Text;
        bool number = "Int32|Int64|Double|Decimal".Contains(_fieldtype);
        string contrlNaeme = this.fieldname.Text;
        sb.AppendFormat("<asp:RequiredFieldValidator runat=\"server\" Display=\"Dynamic\" CssClass=\"notnull\" SetFocusOnError=\"true\" Text=\"不能为空!\" ControlToValidate=\"{0}\"></asp:RequiredFieldValidator>", contrlNaeme);
        if (number || this.fieldtype.Text == "DateTime")
        {
            string dataname = this._fieldname.Text;

            if (number)
            {
                if (_fieldtype == "Int32" || _fieldtype == "Int64")
                {
                    sb.AppendFormat("<asp:RegularExpressionValidator CssClass=\"inputError\" runat=\"server\" SetFocusOnError=\"true\" Text=\"请输入整数!\" ControlToValidate=\"{0}\" ValidationExpression=\"^\\d+$\"></asp:RegularExpressionValidator>", contrlNaeme);
                }
                else
                {
                    sb.AppendFormat("<asp:RegularExpressionValidator CssClass=\"inputError\" runat=\"server\" SetFocusOnError=\"true\" Text=\"请输入小数!\" ControlToValidate=\"{0}\" ValidationExpression=\"^\\d+(?:\\.\\d+)?$\"></asp:RegularExpressionValidator>", contrlNaeme);
                }
            }
            else if (this.fieldtype.Text == "DateTime")
            {
                //sb.AppendFormat("<asp:RegularExpressionValidator CssClass=\"inputError\" runat=\"server\" Text=\"输入正确的日期时间\" ControlToValidate=\"{0}\" ValidationExpression=\"{1}\"></asp:RegularExpressionValidator>", contrlNaeme, @"^\d{4}[/\-][0|1]?[0-2][/\-](?:[0-2]?\d|3[0|1])[/\-\s](?:[0|1]?\d|2[0-3]):[0-5]?\d:[0-5]?\d$");
            }
        }
        return sb;
    }

    private string isDateTime()
    {
        if (this.fieldtype.Text == "DateTime")
        {
            return "onclick=\"WdatePicker({dateFmt:'yyyy/MM/dd HH:mm:ss'})\"";
        }
        return string.Empty;
    }
    private string CreatItems(string ContrlType)
    {
        string _fieldtype = this.fieldtype.Text;
        this.textvalues.CssClass = this.textvalues.CssClass.Replace("error", string.Empty);
        if (ContrlType == ControlTypes.RadioButtonList && _fieldtype == "Boolean")
        {
            IEnumerable<string> arr = this.textvalues.Text.Split('|').Where(x => x != "");
            if (arr.Count() != 2)
            {
                this.textvalues.Focus();
                this.textvalues.CssClass = "show error";
                this.success = false;
                msg = "文本长度错误！请用一对文本分别代表真和假,用|分割。 如  是|否";
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            foreach (string s in arr)
            {
                sb.AppendFormat("\r\n                      <asp:ListItem>{0}</asp:ListItem>", s);
            }
            return sb.ToString();
        }
        else if (this.dataSourcesType.SelectedValue == "0")
        {
            if ("Int32|Int64|Double|Decimal".Contains(_fieldtype))
            {
                IEnumerable<string> pars = this.textvalues.Text.Split('|').Where(x => x != "" && (x.Contains(',') || x.Contains('，')));
                if (pars.Count() < 1)
                {
                    this.textvalues.Focus();
                    this.textvalues.CssClass = "show error";
                    this.success = false;
                    msg = "文本长度错误！键值对数量须大于1对。  如 text1,1|text2,2 (文本,数值) 或 1,1|2,2 (数值,数值)";
                    return string.Empty;
                }
                string[] arr = null;
                StringBuilder sb = new StringBuilder();
                foreach (string s in pars)
                {
                    arr = s.Split(',');
                    if (arr.Length == 0)
                    {
                        arr = s.Split('，');
                    }
                    if (Regex.IsMatch(arr[1], @"^\d+(.\d+)?$", RegexOptions.IgnoreCase))
                    {
                        sb.AppendFormat("\r\n                      <asp:ListItem Value=\"{0}\" >{1}</asp:ListItem>", arr[1], arr[0]);
                    }
                    else
                    {
                        msg = string.Format("数值转换错误！在({0})中，<span>'{1}'<span> 应为数值类型{2}", s, arr[1], _fieldtype);
                    }
                }
                return sb.ToString();
            }
            else
            {
                IEnumerable<string> texts = this.textvalues.Text.Split('|').Where(x => x != "");
                if (texts.Count() < 1)
                {
                    this.textvalues.Focus();
                    this.textvalues.CssClass = "show error";
                    this.success = false;
                    msg = "文本长度错误！文本数量须大于1条。  如 text1|text2|text3  ...";
                    return string.Empty;
                }
                StringBuilder sb = new StringBuilder();
                foreach (string s in texts)
                {
                    sb.AppendFormat("\r\n                      <asp:ListItem>{0}</asp:ListItem>", s);
                }
                return sb.ToString();
            }
        }
        return string.Empty;
    }

    private string CssClass(string ContrlType)
    {
        string css = string.Empty;
        bool number = "Int32|Int64|Double|Decimal".Contains(this.fieldtype.Text.Trim());

        if (number || this.noempty.Checked || this.fieldtype.Text == "DateTime")
        {
            css = "CssClass=\"";
            if (number)
            {
                css += "number";
            }
            else if (this.fieldtype.Text == "DateTime")
            {
                css += "Wdate";
            }
            if (this.noempty.Checked)
            {
                css += " required";
            }
            if (ContrlType == ControlTypes.CheckBoxList)
            {
                css += " ckboxlist";
            }
            else if (ContrlType == ControlTypes.RadioButtonList)
            {
                css += " rdoboxlist";
            }
            css += "\"";
        }
        return css;
    }

    private string SetLength()
    {
        int len = 0;
        if (int.TryParse(this.textLenth.Text, out len) && len > 0)
        {
            return string.Format("MaxLength=\"{0}\"", len);
        }
        return string.Empty;
    }

    private string IsNumber()
    {
        return "";// "Int32|Int64".Contains(this.fieldtype.Text.Trim()) ? "type=\"number\"" : string.Empty;
    }

    private string IsLayoutAble(string ContrlType)
    {
        if (ContrlType == ControlTypes.RadioButtonList || ContrlType == ControlTypes.CheckBoxList)
        {
            if ((this.setboxlist.FindControl("direction") as DropDownList).SelectedIndex != 0)
            {
                return "RepeatLayout=\"Flow\" RepeatDirection=\"Vertical\"";
            }
            int cols = 6;
            int.TryParse((this.setboxlist.FindControl("columns") as DropDownList).SelectedValue, out cols);
            return string.Format("RepeatLayout=\"Flow\" RepeatDirection=\"Horizontal\" RepeatColumns=\"{0}\"", cols);
        }
        return string.Empty;
    }

    private string textCols_Rows()
    {
        int cols = 25;
        int rows = 2;
        int.TryParse((this.settextarea.FindControl("cols") as TextBox).Text, out cols);
        int.TryParse((this.settextarea.FindControl("rows") as TextBox).Text, out rows);
        if (rows < 2)
        {
            rows = 2;
        }
        if (cols < 10)
        {
            cols = 10;
        }
        return string.Format("Rows=\"{0}\" Columns=\"{1}\"", rows, cols);
    }

    #region fields
    public bool UseValidator { get; set; }
    private CheckBox _cid;
    private TextBox _labeltext;
    private TextBox _fieldtype;
    private TextBox _fieldname;
    private TextBox _fieldnull;
    private DropDownList _ctrtype;
    private CheckBox _noempty;
    private TextBox _textLenth;
    private DropDownList _dataSourcesType;
    private TextBox _textvalues;
    private DropDownList _sourcetable;
    private DropDownList _textFiled;
    private DropDownList _valueFiled;
    private Control _settextarea;
    private Control _setboxlist;
    public CheckBox cid { get { if (_cid == null) _cid = findContrlById("cid") as CheckBox; return _cid; } }
    public TextBox labeltext { get { if (_labeltext == null) _labeltext = findContrlById("labeltext") as TextBox; return _labeltext; } }
    public TextBox fieldtype { get { if (_fieldtype == null) _fieldtype = findContrlById("fieldtype") as TextBox; return _fieldtype; } }
    public TextBox fieldname { get { if (_fieldname == null) _fieldname = findContrlById("fieldname") as TextBox; return _fieldname; } }
    public TextBox fieldnull { get { if (_fieldnull == null) _fieldnull = findContrlById("fieldnull") as TextBox; return _fieldnull; } }
    public DropDownList ctrtype { get { if (_ctrtype == null) _ctrtype = findContrlById("ctrtype") as DropDownList; return _ctrtype; } }
    public CheckBox noempty { get { if (_noempty == null) _noempty = findContrlById("noempty") as CheckBox; return _noempty; } }
    public TextBox textLenth { get { if (_textLenth == null) _textLenth = findContrlById("textLenth") as TextBox; return _textLenth; } }
    public DropDownList dataSourcesType { get { if (_dataSourcesType == null) _dataSourcesType = findContrlById("dataSourcesType") as DropDownList; return _dataSourcesType; } }
    public TextBox textvalues { get { if (_textvalues == null) _textvalues = findContrlById("textvalues") as TextBox; return _textvalues; } }
    public DropDownList sourcetable { get { if (_sourcetable == null) _sourcetable = findContrlById("sourcetable") as DropDownList; return _sourcetable; } }
    public DropDownList textFiled { get { if (_textFiled == null) _textFiled = findContrlById("textFiled") as DropDownList; return _textFiled; } }
    public DropDownList valueFiled { get { if (_valueFiled == null) _valueFiled = findContrlById("valueFiled") as DropDownList; return _valueFiled; } }
    public Control settextarea { get { if (_settextarea == null) _settextarea = findContrlById("settextarea"); return _settextarea; } }
    public Control setboxlist { get { if (_setboxlist == null) _setboxlist = findContrlById("setboxlist"); return _setboxlist; } }

    #endregion


}


class TheFrom
{
    private string Name;
    private string Path;
    private int Cols;
    private List<FieldLine> Lines;
    private string msg;
    private string[] Fields;
    private bool hasRadioButtonList;
    private bool hasCheckBoxList;
    private Literal Tips;
    private bool success = true;
    private bool NeedJsPrint;
    private bool UseValidator;
    public TheFrom(string mName, string mPath, int mCols, string[] fields, Literal tips, bool needJsPrint, bool usevalidator)
    {
        Lines = new List<FieldLine>();
        this.Name = mName;
        this.Path = mPath;
        this.Cols = mCols > 1 ? mCols : 1;
        this.Fields = fields;
        this.Tips = tips;
        this.NeedJsPrint = needJsPrint;
        this.UseValidator = usevalidator;
    }
    public int LinrSize()
    {
        return Lines.Count();
    }
    public void AddLine(FieldLine line)
    {
        if (line.fieldname.Text == Fields[1])
        {
            return;
        }
        if (line.ctrtype.SelectedValue == ControlTypes.RadioButtonList)
        {
            hasRadioButtonList = true;
        }
        else if (line.ctrtype.SelectedValue == ControlTypes.CheckBoxList)
        {
            hasCheckBoxList = true;
        }
        line.UseValidator = UseValidator;
        Lines.Add(line);
    }
    public void ToCsCode()
    {

        StringBuilder CsCode = new StringBuilder("using System;\r\n");
        CsCode.Append("using System.Linq;\r\n");
        CsCode.Append("using System.Web.UI.WebControls;\r\n");
        CsCode.Append("using Models;\r\n");
        CsCode.Append("\r\n");
        CsCode.AppendFormat("//------------------------------------------------------------------------------\r\n");
        CsCode.AppendFormat("// <auto-generated>\r\n");
        CsCode.AppendFormat("//    此代码是自动生成的。\r\n");
        CsCode.AppendFormat("//    生成时间: {0}。\r\n", DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"));
        CsCode.AppendFormat("// </auto-generated>\r\n");
        CsCode.AppendFormat("//------------------------------------------------------------------------------\r\n");
        CsCode.AppendFormat("public partial class Form_{0} : {1}\r\n", Name, "AdminBase");
        CsCode.Append("{\r\n");
        CsCode.AppendFormat("    protected {0} _ID;\r\n", Fields[3]);
        CsCode.AppendFormat("    {0} db = new {0}();\r\n", _EasyForm.EntitiesObj.GetType().Name);
        CsCode.Append("    protected void Page_Load(object sender, EventArgs e)\r\n");
        CsCode.Append("    {\r\n");
        CsCode.Append("        string id = Request.QueryString[\"ID\"];\r\n");
        CsCode.Append("        if (!string.IsNullOrEmpty(id))\r\n");
        CsCode.Append("        {\r\n");
        CsCode.AppendFormat("            {0}.TryParse(id, out _ID);\r\n", Fields[3]);
        CsCode.Append("        }\r\n");
        //
        CsCode.Append("        if (!this.IsPostBack)\r\n");
        CsCode.Append("        {\r\n");
        if (needBindContrlData())
        {
            CsCode.Append("            BindContrlsData();\r\n");
        }
        CsCode.Append("            if (_ID > 0)\r\n");
        CsCode.Append("            {\r\n");
        CsCode.Append("                ShowData();\r\n");
        CsCode.Append("            }\r\n");
        CsCode.Append("        }\r\n");
        CsCode.Append("    }\r\n");
        //
        if (needBindContrlData())
        {
            CsCode.Append("    protected void BindContrlsData()\r\n");
            CsCode.Append("    {\r\n");
            CsCode.Append(OnBindDataSource());
            CsCode.Append("    }\r\n");
        }
        //
        CsCode.Append("    protected void ShowData()\r\n");
        CsCode.Append("    {\r\n");
        CsCode.AppendFormat("        {0} Data = db.{0}.FirstOrDefault(a => a.{1} == _ID);\r\n", Name, Fields[0]);
        CsCode.Append("        if (Data == null)\r\n");
        CsCode.Append("        {\r\n");
        CsCode.Append("            return;\r\n");
        CsCode.Append("        }\r\n");
        CsCode.Append(OnShow());
        CsCode.Append("    }\r\n");
        //
        CsCode.Append("    protected void btnSaveClick(object sender, EventArgs e)\r\n");
        CsCode.Append("    {\r\n");
        CsCode.AppendFormat("        {0} Data = db.{0}.FirstOrDefault(a => a.{1} == _ID);\r\n", Name, Fields[0]);
        CsCode.Append("        if (Data == null)\r\n");
        CsCode.Append("        {\r\n");
        CsCode.AppendFormat("            Data = new {0}();\r\n", Name);
        CsCode.AppendFormat("            db.{0}.{1}(Data);\r\n", Name, AddMethod(Name));
        if (!string.IsNullOrEmpty(Fields[1]))
        {
            CsCode.AppendFormat("            Data.{0} = DateTime.Now;\r\n", Fields[1]);
        }
        CsCode.Append("        }\r\n");
        CsCode.Append(getTryVars());
        CsCode.Append("        //\r\n");
        CsCode.Append(this.OnSave());
        if (!string.IsNullOrEmpty(Fields[2]))
        {
            CsCode.AppendFormat("        Data.{0} = DateTime.Now;\r\n", Fields[2]);
        }
        CsCode.Append("        db.SaveChanges();\r\n");
        CsCode.Append("        if (_ID != 0)\r\n");
        CsCode.Append("        {\r\n");
        CsCode.Append("            JscriptPrint(\"保存成功！\",\"\",\"Success\");\r\n");
        CsCode.Append("            ShowData();\r\n");
        CsCode.Append("        }\r\n");
        CsCode.Append("        else{\r\n");
        CsCode.AppendFormat("            _ID = Data.{0};\r\n", Fields[0]);
        CsCode.Append("            JscriptPrint(\"保存成功！\", \"?ID=\" + _ID,\"Success\");\r\n");
        CsCode.Append("        }\r\n");
        CsCode.Append("    }\r\n");

        if (hasCheckBoxList)
        {
            CsCode.Append("    protected void BindCheckBoxList(CheckBoxList boxlist, string str)\r\n");
            CsCode.Append("    {\r\n");
            CsCode.Append("        if (string.IsNullOrEmpty(str))\r\n");
            CsCode.Append("        {\r\n");
            CsCode.Append("            return;\r\n");
            CsCode.Append("        }\r\n");
            CsCode.Append("        //多选框可以有多值，以 | 为分割\r\n");
            CsCode.Append("        string[] values = str.Split('|');\r\n");
            CsCode.Append("        if (values.Length == 0)\r\n");
            CsCode.Append("        {\r\n");
            CsCode.Append("            return;\r\n");
            CsCode.Append("        }\r\n");
            CsCode.Append("        var its = boxlist.Items;\r\n");
            CsCode.Append("        ListItem it = null;\r\n");
            CsCode.Append("        foreach (var s in values)\r\n");
            CsCode.Append("        {\r\n");
            CsCode.Append("            it = its.FindByValue(s);\r\n");
            CsCode.Append("            if (it == null)\r\n");
            CsCode.Append("            {\r\n");
            CsCode.Append("                it = its.FindByText(s);\r\n");
            CsCode.Append("            }\r\n");
            CsCode.Append("            if (it != null)\r\n");
            CsCode.Append("            {\r\n");
            CsCode.Append("                it.Selected = true;\r\n");
            CsCode.Append("            }\r\n");
            CsCode.Append("        }\r\n");
            CsCode.Append("    }\r\n");
            CsCode.Append("    protected string GetCheckBoxListValues(CheckBoxList boxlist)\r\n");
            CsCode.Append("    {\r\n");
            CsCode.Append("        string values = \"\";\r\n");
            CsCode.Append("        var its = boxlist.Items;\r\n");
            CsCode.Append("        if (its.Count == 0)\r\n");
            CsCode.Append("        {\r\n");
            CsCode.Append("            return values;\r\n");
            CsCode.Append("        }\r\n");
            CsCode.Append("        foreach (ListItem i in its)\r\n");
            CsCode.Append("        {\r\n");
            CsCode.Append("            if (i.Selected)\r\n");
            CsCode.Append("            {\r\n");
            CsCode.Append("                values += i.Value + \"|\";\r\n");
            CsCode.Append("            }\r\n");
            CsCode.Append("        }\r\n");
            CsCode.Append("        return values;\r\n");
            CsCode.Append("    }\r\n");
        }
        //
        if (NeedJsPrint)
        {
            CsCode.Append("    protected void JscriptPrint(string msgtitle, string url, string msgcss)\r\n");
            CsCode.Append("    {\r\n");
            CsCode.Append("        string msbox = \"\";\r\n");
            CsCode.Append("        msbox += \"<script type=\\\"text/javascript\\\">\\n\";\r\n");
            CsCode.Append("        msbox += \"    top.jsprint('\" + msgtitle + \"','\" + url + \"','\" + msgcss + \"')\\n\";\r\n");
            CsCode.Append("        if (!string.IsNullOrEmpty(url))\r\n");
            CsCode.Append("        {\r\n");
            CsCode.Append("             msbox += \"    winndow.location.href='\" + url + \"'\\n\";\r\n");
            CsCode.Append("        }\r\n");
            CsCode.Append("        msbox += \"</script>\\n\";\r\n");
            CsCode.Append("        ClientScript.RegisterClientScriptBlock(Page.GetType(), \"JsPrint\", msbox);\r\n");
            CsCode.Append("    }\r\n");
        }
        CsCode.Append("}");

        WriteFile(Path, string.Format("{0}.aspx.cs", this.Name), CsCode.ToString());
    }

    private string AddMethod(string tableName)
    {
        Entities db = new Entities();
        Type ts = db.GetType();
        PropertyInfo pi = ts.GetProperties().FirstOrDefault(a => a.Name.ToLower() == tableName.ToLower());
        if (pi == null)
        {
            return null; ;
        }
        var v = pi.GetValue(db, null);  //获取一个 ObjectSet<> 或 DbSet<>
        //                                                               ObjectSet<>           DbSet<>
        return v.GetType().GetMethods().FirstOrDefault(a => a.Name == "AddObject" || a.Name == "Add").Name;
    }
    private bool needBindContrlData()
    {
        return this.Lines.Where(x => x.dataSourcesType.SelectedIndex == 1).Count() > 0;
    }
    private StringBuilder getTryVars()
    {
        StringBuilder sb = new StringBuilder();
        string types = "Int32|Int64|Double|Decimal|DateTime";
        string type = "";
        foreach (var l in Lines)
        {
            type = l.fieldtype.Text;
            if (types.Contains(type))
            {
                types = types.Replace(type, string.Empty);
                sb.AppendFormat("        {0} _{1} = {2};\r\n", type, type.ToLower(), type == "DateTime" ? "DateTime.Now" : "0");
            }
        }

        return sb;
    }
    private StringBuilder OnBindDataSource()
    {
        StringBuilder sb = new StringBuilder();
        StringBuilder s = null;
        foreach (var l in Lines)
        {
            s = l.OnBindDataSource();
            if (s != null)
            {
                sb.Append(s);
                sb.Append("        //\r\n");
            }
            if (l.IsSuccess())
            {
                Tips.Text += l.getMsg();
            }
            else
            {
                success = false;
                Tips.Text = "<span style='color:red'>严重错误：" + l.getMsg() + "</span>";
                return sb;
            }
        }
        return sb;
    }
    private StringBuilder OnShow()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var l in Lines)
        {
            sb.AppendFormat("        {0}\r\n", l.OnShow());
            if (l.IsSuccess())
            {
                Tips.Text += l.getMsg();
            }
            else
            {
                success = false;
                Tips.Text = "<span style='color:red'>严重错误：" + l.getMsg() + "</span>";
                return sb;
            }
        }
        return sb;
    }

    private StringBuilder OnSave()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var l in Lines)
        {
            sb.Append(l.OnSave());
        }
        return sb;
    }
    public void ToForm()
    {
        StringBuilder sb = new StringBuilder("<%@ Page Language=\"C#\" AutoEventWireup=\"true\"");
        sb.AppendFormat("CodeFile=\"{0}.aspx.cs\" Inherits=\"Form_{0}\"  %>\r\n", this.Name);
        sb.Append("\r\n");
        sb.Append("<!DOCTYPE html>\r\n");
        sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
        sb.Append("<head>\r\n");
        sb.Append("     <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n");
        sb.AppendFormat("     <title>{0}</title>\r\n", this.Name);
        sb.Append("     <link rel=\"stylesheet\" type=\"text/css\" href=\"/admin/images/style.css\" />\r\n");
        sb.Append("     <style type=\"text/css\">\r\n");
        sb.Append("          .notnull, .inputError\r\n");
        sb.Append("          {\r\n");
        sb.Append("              font-size: 12px;\r\n");
        sb.Append("              padding: 3px;\r\n");
        sb.Append("              text-indent: 5px;\r\n");
        sb.Append("              color: Red;\r\n");
        sb.Append("              padding-left: 18px;\r\n");
        sb.Append("              background:url() left center no-repeat;\r\n");
        sb.Append("          }\r\n");
        sb.Append("     </style>\r\n");
        sb.Append("</head>\r\n");
        sb.Append("<body>\r\n");
        sb.Append("<div class=\"navigation\">\r\n");
        sb.Append("     <span class=\"back\"><a href=\"List.aspx\">返回列表</a></span><b>您当前的位置：首页 &gt; xxx &gt; yyyy</b>\r\n");
        sb.Append("</div>\r\n");
        sb.Append("<form id=\"form1\" runat=\"server\">\r\n");
        sb.Append("     <div>\r\n");
        sb.Append("         <table id='datatable' width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"msgtable\">\r\n");
        int i = 1;
        foreach (var l in Lines)
        {
            sb.Append(l.ToFormLine(i, Cols));
            if (l.IsSuccess())
            {
                Tips.Text += l.getMsg();
            }
            else
            {
                success = false;
                Tips.Text = "<span style='color:red'>严重错误：" + l.getMsg() + "</span>";
                return;
            }
            i += 1;
        }
        if (Lines.Count % Cols != 0)
        {
            sb.AppendFormat("                 <td class='empty' colspan=\"{0}\"></td></tr>\r\n", (Cols - Lines.Count % Cols) * 2);
        }
        sb.AppendFormat("             <tr class='save'>\r\n                  <td class='save_td_left'>&nbsp;</td>\r\n                  <td class='save_td_right' colspan=\"{0}\"><asp:Button ID=\"save\" class='submit save' runat=\"server\" OnClick=\"btnSaveClick\" Text=\"保存\" /></td>\r\n             </tr>\r\n", Cols * 2 - 1);
        sb.Append("         </table>\r\n");
        sb.Append("     </div>\r\n");
        sb.Append("</form>\r\n");
        sb.Append("</body>\r\n");
        sb.Append("</html>\r\n");
        WriteFile(Path, string.Format("{0}.aspx", this.Name), sb.ToString());
    }

    public void CreatCode(ref string msg)
    {
        ToForm();
        ToCsCode();
        if (success)
        {
            Tips.Text += string.Format("<span style='color:green;'>&nbsp;&nbsp;操作成功！-<a href='/{0}/{1}.aspx' target='_blank'>查看</a></span>", "EasyFormPages", this.Name);
        }
    }

    protected void WriteFile(string path, string name, string text)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        name = path + name;
        try
        {
            File.WriteAllText(name, text, Encoding.UTF8);
        }
        catch (Exception e)
        {
            Tips.Text = e.Message;
        }
    }
}

sealed class TableField
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string NullAble { get; set; }
}

sealed class ControlTypes
{
    public static string TextBox_SingleLine = "TextBox-单行";
    public static string TextBox_MultiLine = "TextBox-多行";
    public static string TextBox_Password = "TextBox-密码";
    public static string DropDownList = "DropDownList";
    public static string ListBox = "ListBox";
    public static string RadioButtonList = "RadioButtonList";
    public static string CheckBox = "CheckBox";
    public static string CheckBoxList = "CheckBoxList";
}
#endregion